package com.nytd.demo.configuration;

import com.nytd.demo.entity.Result;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.stream.Collectors;

@ControllerAdvice
@ResponseBody
public class ErrorAdvice {

    @ExceptionHandler(NullPointerException.class)
    public Result<Object> handleNullPointerException(NullPointerException ex) {
        return Result.fail(500, "空指针错误: " + ex.getMessage());
    }


    @ExceptionHandler(ArithmeticException.class)
    public Result<Object> handleArithmeticException(ArithmeticException ex) {
        return Result.fail(500, "计算错误: " + ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result<Object> handleValidationException(MethodArgumentNotValidException ex) {
        String errorMessage = ex.getBindingResult().getFieldErrors().stream()
                .map(FieldError::getDefaultMessage)
                .collect(Collectors.joining(", "));
        return Result.fail(400, "参数校验失败: " + errorMessage);
    }

    @ExceptionHandler(Exception.class)
    public Result<Object> handleAllExceptions(Exception ex) {
        return Result.fail(500, "系统错误: " + ex.getMessage());
    }


}
